package org.prs.persistence.member;

import com.prs.util.PrsException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.prs.model.member.Member;
import org.prs.persistence.connector.MySQLDatabaseConnector;

public class MemberDatabasePersistenceManager {

    Connection conn;
    private ResultSet result;
    public boolean insertMember(Member member) {
        boolean inserted = true;
        PreparedStatement insertMember = null;
        conn = MySQLDatabaseConnector.getConnection();
        try {
            insertMember = conn.prepareStatement("insert into member set firstname=?, lastname=?, middlename=?, gender=?, "
                    + "departmentid=?");
            insertMember.setString(1, member.getFirstName());
            insertMember.setString(2, member.getLastName());
            insertMember.setString(3, member.getMiddleName());
            insertMember.setString(4, member.getGender());
            insertMember.setInt(5, member.getDepartmentId());
            insertMember.executeUpdate();
        } catch (SQLException e) {
            throw new PrsException(e);
        }

        return inserted;
    }
     public List<Member> getMembers() {
        PreparedStatement selectMember = null;
        List<Member> members=new ArrayList<Member>();
        conn = MySQLDatabaseConnector.getConnection();
        try {
            selectMember = conn.prepareStatement("select * from member");            
           result=selectMember.executeQuery();
           while(result.next()){
               members.add(getMember(result));
           }
        } catch (SQLException e) {
            throw new PrsException(e);
        }

        return members;
    }
     public Member getMember(ResultSet result){
         Member member=new Member();
         try{
             member.setGender(result.getString("gender"));
             member.setDepartmentId(result.getInt("departmentid"));
             member.setFirstName(result.getString("firstname"));
             member.setId(result.getInt("id"));
             member.setLastName(result.getString("lastname"));
             member.setMiddleName(result.getString("middlename"));
         }catch(SQLException e){
             
         }
         return member;
     }
}
